package com.nord.NewsList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.nord.R;
import com.nord.Menus.Menus;
import com.nord.R.id;
import com.nord.R.layout;
import com.nord.Services.SQLiteAdapter;
import com.nord.WebTools.HtmlBrowser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


public class NewsList extends Activity {
	/*
	 * Data invariant: + newsInfo is a List of HashMaps - HashMaps include
	 * name,author and date of post + listView is the ListView actvitiy widget
	 */

	private List<HashMap<String, String>> newsInfo;
	private ListView listView;

	@Override
	public void onResume() {
		super.onResume();
		setContentView(R.layout.activity_news_list);

		listView = (ListView) findViewById(R.id.listView);
		Button newsBanner = (Button) findViewById(R.id.newsBanner);
		Typeface tf = Typeface.createFromAsset(getAssets(),"DaysOne-Regular.ttf");
		newsBanner.setTypeface(tf);

		new NewsProcessor().execute();

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent selection = new Intent(arg1.getContext(), NewsFeed.class);
				selection.putExtra("TITLE",newsInfo.get(position).get("title"));
				selection.putExtra("BODY",newsInfo.get(position).get("body"));
				selection.putExtra("ID",newsInfo.get(position).get("id"));
				selection.putExtra("LIKERS",newsInfo.get(position).get("likers"));
				selection.putExtra("LOVERS",newsInfo.get(position).get("lovers"));
				selection.putExtra("COMMENTS",newsInfo.get(position).get("comments"));
				selection.putExtra("SLUG",newsInfo.get(position).get("slug"));
				if(newsInfo.get(position).get("liked") != null){
					selection.putExtra("LIKED","true");
				}
				if(newsInfo.get(position).get("loved") != null){
					selection.putExtra("LOVED","true");
				}

				startActivity(selection);
			}
		});
	}

	private class NewsProcessor extends AsyncTask<Void, Integer, Boolean> {
		ProgressDialog progressBar;
		SimpleAdapter adapter;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(NewsList.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að sækja nýjustu fréttir frá www.nord.is ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			String[] htmlInfo = HtmlBrowser.getExecutor(
					"http://www.nord.is/api/nord/news/?format=json&limit=10");			
			if(!htmlInfo[0].contains("Exception")){
				newsInfo = HtmlBrowser.jsonNewsProcessor(htmlInfo[0], NewsList.this,getIntent().getExtras().getString("USERNAME"));
				return true;
			} else {
				String[] columns = new String[] { 
						"title",
						"body", 
						"date", 
						"id",
						"translation",
						"likers",
						"lovers",
						"comments",
						"author",
						"slug"};
				SQLiteAdapter sql = new SQLiteAdapter(NewsList.this);
				sql.open("R");
				Cursor cursor = sql.queryTable("news", columns);
				if(cursor.getCount() != 0){
					if(cursor.moveToFirst()){
						newsInfo = new ArrayList<HashMap<String,String>>();
						for(int i = 0; i < cursor.getCount(); i++){
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("title", cursor.getString(cursor.getColumnIndex("title")));
							map.put("body", cursor.getString(cursor.getColumnIndex("body")));
							map.put("date", cursor.getString(cursor.getColumnIndex("date")));
							map.put("id",cursor.getString(cursor.getColumnIndex("id")));
							map.put("translation", cursor.getString(cursor.getColumnIndex("translation")));
							map.put("likers",cursor.getString(cursor.getColumnIndex("likers")));
							map.put("lovers", cursor.getString(cursor.getColumnIndex("lovers")));
							map.put("comment_url",cursor.getString(cursor.getColumnIndex("comments")));
							map.put("author",cursor.getString(cursor.getColumnIndex("author")));
							map.put("slug",cursor.getString(cursor.getColumnIndex("slug")));
							newsInfo.add(map);
							cursor.moveToNext();
						}
					}
					cursor.close();
					sql.close();
					return true;
				} else 
					return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean status) {
			progressBar.dismiss();
			if(status){
				String[] from = { "title", "date", "author" };
				int[] to = { R.id.title, R.id.date, R.id.author };
				adapter = new NewsListAdapter(NewsList.this, newsInfo, R.layout.list_news_list, from, to);
				listView.setAdapter(adapter);
			} else {
				Intent menus = new Intent(NewsList.this, Menus.class);
				menus.putExtra("USERNAME", getIntent().getExtras().getString("USERNAME"));
				Toast.makeText(getApplicationContext(), "Engar fréttir í gagnagrunni", Toast.LENGTH_LONG).show();
				startActivity(menus);
			}
		}
	}
}
